<template>
  <div class="login-container">
    <div class="login-box">
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title">{{ systemName }}</h3>
        </div>
        <el-form-item prop="username">
          <span class="svg-container">
            <el-icon><Avatar /></el-icon>
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            class="login-input"
            placeholder="请输入账户名称"
            name="username"
            type="text"
            tabindex="1"
            autocomplete="on"
            @change="changeUsername"
          >
          </el-input>
        </el-form-item>
        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <span class="svg-container">
              <el-icon><Unlock /></el-icon>
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              class="login-input"
              :type="passwordType"
              placeholder="请输入账户密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              @keyup="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <el-icon>
                <View v-if="passwordType !== 'password'" />
                <Hide v-if="passwordType === 'password'" />
              </el-icon>
            </span>
          </el-form-item>
        </el-tooltip>
        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="verificationCode" v-if="isNeedVerificationCode">
            <el-input
              ref="verificationCode"
              v-model="loginForm.verificationCode"
              type="text"
              class="login-input"
              placeholder="请输入验证码"
              name="verificationCode"
              tabindex="3"
              autocomplete="on"
              @keyup="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter="handleLogin"
              style="width: 200px"
            />
            <img :src="verificationCodeImg" @click="_getVerify" />
          </el-form-item>
        </el-tooltip>
        <el-button
          :loading="loading"
          type="primary"
          class="btn-login"
          style="width: 100%; margin-bottom: 30px"
          @click.prevent="handleLogin"
          >登录</el-button
        >
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { getCoreSystemConfigGetConfigValue } from '@/api/core'
import { getVerify, getIsNeedVerify, validationVerifyCode } from '@/api/pub'
import { useRoute, useRouter } from 'vue-router'
const $route = useRoute()
const $router = useRouter()
const { proxy } = getCurrentInstance()
const systemName = ref('')
const login_verification_code = ref('')
const login_verification_code_time = ref('')

let isNeedVerificationCode = ref(false)
const verificationCodeImg = ref('')
const loginForm = ref({
  username: '',
  password: '',
  verificationCode: '',
})
const loginRules = ref({
  username: [
    {
      required: true,
      trigger: 'blur',
      message: proxy.$t('null_user_account'),
    },
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: proxy.$t('null_user_password'),
    },
  ],
  verificationCode: [
    {
      required: true,
      trigger: 'blur',
      message: proxy.$t('null_user_verificationCode'),
    },
  ],
})
const passwordType = ref('password')
const capsTooltip = ref(false)
const loading = ref(false)
const redirect = ref(undefined)
const otherQuery = ref({})
const nonceStr = ref('')
watch(
  () => $route,
  (val) => {
    const query = val.query
    if (query) {
      redirect.value = query.redirect
      otherQuery.value = getOtherQuery(query)
    }
  },
  {
    immediate: true,
  }
)

watch(
  () => isNeedVerificationCode.value,
  (val) => {
    if (val) {
      _getVerify()
    }
  },
  {
    deep: true,
    immediate: true,
  }
)

onMounted(() => {
  if (loginForm.value.username === '') {
    proxy.$refs.username.focus()
  } else if (loginForm.value.password === '') {
    proxy.$refs.password.focus()
  }
})

//获取验证码
const _getVerify = () => {
  getVerify({ verificationKey: nonceStr.value }).then((res) => {
    if (res.success) {
      verificationCodeImg.value = 'data:image/gif;base64,' + res.data
    }
  })
}
const changeUsername = (value) => {
  loginForm.value.username = value
}
const getSystemNameValue = () => {
  getCoreSystemConfigGetConfigValue({
    systemConfigCode: 'system_name',
  }).then((res) => {
    if (res && res.success) {
      systemName.value = res.data
    }
  })
  getNeedVerify()
}
function getNeedVerify(){
  let verificationKey = localStorage.getItem('verificationKey')
  if(verificationKey){
    nonceStr.value = verificationKey
  }else{
    let uuid = Math.random().toString(36).slice(-6) + (1 + Math.random())
    let timestamp = Math.floor(Date.now() / 1000)
    nonceStr.value = uuid + ':' + timestamp
    localStorage.setItem('verificationKey', nonceStr.value)
  }
  getIsNeedVerify({ verificationKey: nonceStr.value }).then((res) => {
    if (res.success && res.data) {
      isNeedVerificationCode.value = true
    }
  })
}
const checkCapslock = ({ shiftKey, key } = {}) => {
  if (key && key.length === 1) {
    if (
      (shiftKey && key >= 'a' && key <= 'z') ||
      (!shiftKey && key >= 'A' && key <= 'Z')
    ) {
      capsTooltip.value = true
    } else {
      capsTooltip.value = false
    }
  }
  if (key === 'CapsLock' && capsTooltip.value === true) {
    capsTooltip.value = false
  }
}
const showPwd = () => {
  if (passwordType.value === 'password') {
    passwordType.value = ''
  } else {
    passwordType.value = 'password'
  }
  proxy.$nextTick(() => {
    proxy.$refs.password.focus()
  })
}
const handleLogin = () => {
  proxy.$refs.loginFormRef.validate((valid) => {
    if (valid) {
      if (isNeedVerificationCode.value) {
        //先校验验证码是否正确
        let params = {
          verificationKey: nonceStr.value,
          verificationCode: loginForm.value.verificationCode,
        }
        validationVerifyCode(params).then((res) => {
          if (res.success) {
            if (!res.data) {
              _getVerify()
              proxy.$message.error({
                message: '验证码错误请重新输入',
                showClose: true,
                duration: 3000,
              })
              loginForm.value.verificationCode = ''
              return
            } else {
              if(nonceStr.value){
                loginForm.value['verificationKey'] = nonceStr.value
              }
              loading.value = true
              proxy.$store
                .dispatch('user/login', loginForm.value)
                .then((res) => {
                  if (res) {
                    $router.push({
                      path: redirect.value || '/',
                      query: otherQuery.value,
                    })
                    if(loginForm.value['verificationKey']){
                      delete loginForm.value['verificationKey']
                    }
                    nonceStr.value = ''
                    localStorage.removeItem('verificationKey')
                  }
                  loading.value = false
                })
                .catch(() => {
                  _getVerify()
                  loading.value = false
                })
            }
          }
        })
      } else {
        // getIsNeedVerify({ verificationKey: nonceStr.value }).then((resf) => {
        //   if (resf.success && resf.data) {
        //     isNeedVerificationCode.value = true
        //     return
        //   } else {
            
        //   }
        // })
        if(nonceStr.value){
          loginForm.value['verificationKey'] = nonceStr.value
        }
        loading.value = true
        proxy.$store
          .dispatch('user/login', loginForm.value)
          .then((res) => {
              if (res) {
                $router.push({
                  path: redirect.value || '/',
                  query: otherQuery.value,
                })
                if(loginForm.value['verificationKey']){
                  delete loginForm.value['verificationKey']
                }
                  nonceStr.value = ''
                  localStorage.removeItem('verificationKey')
              }else{
                getNeedVerify()
              }
              loading.value = false
            })
            .catch(() => {
              loading.value = false
              getNeedVerify()
            })
      }
    } else {
      return false
    }
  })
}
function getOtherQuery(query) {
  return Object.keys(query).reduce((acc, cur) => {
    if (cur !== 'redirect') {
      acc[cur] = query[cur]
    }
    return acc
  }, {})
}
getSystemNameValue()
</script>

<style lang="scss">
$bg: rgba(0, 0, 0, 0.44);
$light_gray: #fff;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input__wrapper {
    background: none;
    width: 100%;
    box-shadow: none;
  }
  .el-input {
    display: inline-block;
    height: 42px;
    width: 81%;
    input {
      border: 0px;
      background: transparent !important;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 11px 5px 11px 5px;
      color: $light_gray;
      height: 42px;
      caret-color: $cursor;
      &:-internal-autofill-previewed,
      &:-internal-autofill-selected {
        -webkit-text-fill-color: #ffffff !important;
        transition: background-color 5000s ease-in-out 0s !important;
      }
    }
    .el-input__wrapper {
      height: 100%;
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #adbfc9;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background: url('../../assets/image/sm-bg.jpg') no-repeat center center/cover;
  overflow: hidden;

  .login-box {
    width: 400px;
    height: 340px;
    background: rgba(0, 0, 0, 0.3);
    margin: 0 auto;
    position: absolute;
    right: 10%;
    bottom: calc(50% - 170px);
    .login-form {
      position: relative;
      /*width: 520px;*/
      max-width: 75%;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      /*width: 30px;*/
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        color: white;
        font-size: 26px;
        text-align: center;
        padding: 20px 0;
        margin-top: 20px;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
    .btn-login {
      height: 32px !important;
      line-height: 32px !important;
    }
  }
}
</style>
